let fs = require('fs');

module.exports = (req, res, next) => {
    let params = req.body;

    if(req.files){
        let files = req.files.file,         //文件
            fileName = files.name,          //文件名
            source = fs.createReadStream(files.path),   // 创建文件
            suffixSplit = fileName.split('.'),
            suffix = suffixSplit[suffixSplit.length - 1],     //截取后缀
            outputUrl = '/avater/' + params.mobile + '.' + suffix,
            saveFile = fs.createWriteStream(process.cwd() + '/public' + outputUrl);
        
        // 保存文件
        source.pipe(saveFile);
        source.on('end', function() {
            // 删除临时文件
            fs.unlinkSync(files.path);
            
            res.json({
                result: 1,
                data: {
                    path: outputUrl,
                    name: fileName
                }
            })
        });   
        source.on('error', function(err) {
            res.json(resFail(JSON.stringify(err)))
        });
    }else{
        res.json(resFail('无法获取上传的文件'))
    }
}